package com.tencent.examples.core.processor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencent.bk.utils.blueking.tools.AnalysisObjectList;
import com.tencent.bk.utils.blueking.tools.StringConverters;
import com.tencent.examples.blueking.extend.QueryParam;
import com.tencent.examples.blueking.mongo.model.ObjectBase;
import com.tencent.examples.blueking.mongo.service.ObjectBaseService;
import com.tencent.examples.blueking.mysql.model.BkMessage;
import com.tencent.examples.blueking.mysql.service.BkStoreTimeService;
import com.tencent.examples.blueking.mysql.service.MessageService;
import com.tencent.examples.core.processor.common.BkobjidEnum;
import com.tencent.examples.core.processor.dto.BkInstDto;
import com.tencent.examples.core.processor.dto.BkItopInstDto;
import com.tencent.examples.core.processor.dto.BkMqInstDto;
import com.tencent.examples.core.processor.dto.BkResult;
import com.tencent.examples.core.processor.mq.MQConnect;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author :  CHENWEN
 * @Description :信息解析器
 * @Creation Date:  2019/3/28
 */
@Component
public class MessageProcessor {
    private static final Logger logger = LoggerFactory.getLogger(MessageProcessor.class);

    private final String MQSTOREIDKEY = "ops_global_id";
    private final String ITOPSTOREIDKEY = "store_code";

    @Autowired
    BlueKingProcessor blueKingProcessor;
    @Autowired
    ObjectBaseService objectBaseService;
    @Autowired
    MessageService messageService;
    @Autowired
    BkStoreTimeService bkStoreTimeService;

    /**
     * 同步门店实例，单个同步
     *
     * @param syncData 待同步的数据
     * @param mqMessId 本地mqMessageId
     */
    @SuppressWarnings("unchecked")
//    ConcurrentHashMap<String, Object> syncData
    public void syncStore(BkobjidEnum mxid, JSONObject syncData, int mqMessId) {
        if (syncData == null) {
            return;
        }

        List bkJkInstDtos = blueKingProcessor.jkSearchProcessor(mxid);
        if (bkJkInstDtos == null || bkJkInstDtos.size() <= 0) {
            return;
        }

        String bk_obj_id = null;
        BkMessage bkMessage = BkMessage.builder()
                .source(mxid.name())
                .message(JSON.toJSONString(syncData))
                .topic(MQConnect.CATTRIB_NAME)
                .build();

        if (bkJkInstDtos.get(0) instanceof BkMqInstDto) {
            bkMessage.setMx(((BkMqInstDto) bkJkInstDtos.get(0)).getMx());
            bk_obj_id = ((BkMqInstDto) bkJkInstDtos.get(0)).getMx();
        } else if (bkJkInstDtos.get(0) instanceof BkItopInstDto) {
            bkMessage.setMx(((BkItopInstDto) bkJkInstDtos.get(0)).getMx());
            bk_obj_id = ((BkItopInstDto) bkJkInstDtos.get(0)).getMx();
        }

        //是否存本地
        if (mqMessId <= 0) {
            bkMessage.setSync(0);
            messageService.messageSave(bkMessage);
        } else {
            bkMessage.setId(mqMessId);
        }

        AtomicReference<String> bkKeyId = new AtomicReference<>("");
        //待蓝鲸上传的数据
        ConcurrentHashMap<String, Object> bkMap = new ConcurrentHashMap<>();

        bkJkInstDtos.forEach(bkMqInstDto -> {
            if (bkMqInstDto instanceof BkMqInstDto) {
                //蓝鲸的key
                String bkKey = ((BkMqInstDto) bkMqInstDto).getZd();
                //mq的key
                String mqKey = ((BkMqInstDto) bkMqInstDto).getMqzd();
                if (MQSTOREIDKEY.equals(mqKey)) {
                    bkKeyId.set(bkKey);
                }
                if (syncData.get(mqKey) != null) {
                    bkMap.put(bkKey, syncData.get(mqKey) + "");
                }
            } else if (bkMqInstDto instanceof BkItopInstDto) {
                //蓝鲸的key
                String bkKey = ((BkItopInstDto) bkMqInstDto).getZd();
                //itop的key
                String itopKey = ((BkItopInstDto) bkMqInstDto).getItop();
                if (ITOPSTOREIDKEY.equals(itopKey)) {
                    bkKeyId.set(bkKey);
                    if (syncData.get(itopKey) != null) {
                        bkMap.put(bkKey, (syncData.get(itopKey) + "").replace("S", ""));
                    }
                } else {
                    if (syncData.get(itopKey) != null) {
                        bkMap.put(bkKey, syncData.get(itopKey) + "");
                    }
                }
            }

        });

        if (bkMap.size() <= 0) {
            return;
        }

        //监测当前实例id是否存在
        List<BkInstDto> bkInstDtos = blueKingProcessor.searchInstProcessor(bk_obj_id, bkKeyId.get(), bkMap.get(bkKeyId.get()) + "");
        BkResult result;
        if (bkInstDtos == null || bkInstDtos.size() <= 0) {//新增
            result = blueKingProcessor.createInstProcessor(bk_obj_id, bkMap);
        } else {//修改
            bkMap.put("bk_inst_id", bkInstDtos.get(0).getBk_inst_id());
            result = blueKingProcessor.updateInstProcessor(bk_obj_id, bkMap);
        }

        if (result != null && result.isResult()) {//代表数据提交成功
            bkMessage.setSync(1);
            messageService.update(bkMessage);
        }

        assert result != null;
        logger.info("同步信息返回--->" + result.getMessage());
    }


    /**
     * 同步门店时间实例，单个同步
     *
     * @param syncData 待同步的数据
     * @param mqMessId 本地mqMessageId
     */
    @SuppressWarnings("unchecked")
    public void syncStoreHours(BkobjidEnum mxid, JSONObject syncData, int mqMessId) {

        if (syncData == null) {
            return;
        }
        String bk_obj_id = null;

        List bkJkInstDtos = blueKingProcessor.jkSearchProcessor(mxid);
        if (bkJkInstDtos == null || bkJkInstDtos.size() <= 0) {
            return;
        }

        BkMessage bkMessage = BkMessage.builder()
                .source(mxid.name())
                .message(JSON.toJSONString(syncData))
                .topic(MQConnect.CATTRIB_NAME_HOURS)
                .build();

        if (bkJkInstDtos.get(0) instanceof BkMqInstDto) {
            bkMessage.setMx(((BkMqInstDto) bkJkInstDtos.get(0)).getMx());
            bk_obj_id = ((BkMqInstDto) bkJkInstDtos.get(0)).getMx();
        }

        QueryParam queryParam = new QueryParam();
        String global_id = AnalysisObjectList.ObjectString(syncData, "global_id");
        String store_name = AnalysisObjectList.ObjectString(syncData, "store_name");
        String begin_date = AnalysisObjectList.ObjectString(syncData, "begin_date");
        String end_date = AnalysisObjectList.ObjectString(syncData, "end_date");
        String business_open_time = AnalysisObjectList.ObjectString(syncData, "business_open_time");
        String business_close_time = AnalysisObjectList.ObjectString(syncData, "business_close_time");
        Integer day_of_week_mon1_sun7 = AnalysisObjectList.ObjectInteger(syncData, "day_of_week_mon1_sun7");
        if (StringUtils.isEmpty(global_id) || day_of_week_mon1_sun7 == null) {
            return;
        }
        if (StringUtils.isEmpty(begin_date) && StringUtils.isEmpty(end_date) && StringUtils.isEmpty(business_open_time) & StringUtils.isEmpty(business_close_time)) {
            return;
        }
        queryParam.getSqlMap().put("global_id", global_id);
        queryParam.getSqlMap().put("bk_obj_id", bk_obj_id);
        if (StringUtils.isNotEmpty(begin_date) && StringUtils.isNotEmpty(business_open_time)) {
            queryParam.getSqlMap().put("weekStart", day_of_week_mon1_sun7 + "");
        }
        if (StringUtils.isNotEmpty(end_date) && StringUtils.isNotEmpty(business_close_time)) {
            queryParam.getSqlMap().put("weekClose", day_of_week_mon1_sun7 + "");
        }
        List<ObjectBase> objectBaseList = objectBaseService.searchAll(queryParam);
        if (CollectionUtils.isEmpty(objectBaseList)) {
            return;
        }
        ObjectBase objectBase = objectBaseList.get(0);
        //是否存本地
        if (mqMessId <= 0) {
            bkMessage.setSync(0);
            messageService.messageSave(bkMessage);
        } else {
            bkMessage.setId(mqMessId);
        }

        //待蓝鲸上传的数据
        ConcurrentHashMap<String, Object> bkMap = new ConcurrentHashMap<>();

        bkMap.put("bk_inst_id", objectBase.getBk_inst_id());
        if (StringUtils.isNotEmpty(begin_date) && StringUtils.isNotEmpty(business_open_time)) {
            bkMap.put("store_" + day_of_week_mon1_sun7 + "start_time", begin_date + " " + business_open_time);
        }
        if (StringUtils.isNotEmpty(end_date) && StringUtils.isNotEmpty(business_close_time)) {
            bkMap.put("store_" + day_of_week_mon1_sun7 + "close_time", end_date + " " + business_close_time);
        }
        BkResult result = blueKingProcessor.updateInstProcessor(bk_obj_id, bkMap);
        if (result != null && result.isResult()) {//代表数据提交成功
            bkMessage.setSync(1);
            messageService.update(bkMessage);
            //开始更新门店表的开闭店时间
            bkStoreTimeService.messageSaveStore(StringConverters.ToLong(global_id), store_name, begin_date, end_date
                    , business_open_time, business_close_time, day_of_week_mon1_sun7, objectBase.getBk_inst_id());
        }
        assert result != null;
//        logger.info("同步信息返回--->" + result.getMessage());

//        logger.info("同步信息返回--->");
    }
}
